package com.situ.allaia.controller;

import com.situ.allaia.common.Global;
import com.situ.allaia.model.Order;
import com.situ.allaia.model.User;
import com.situ.allaia.model.UserAddress;
import com.situ.allaia.service.OrderService;
import com.situ.allaia.service.UserAddressService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/personal")
public class PersonalController {
    private final OrderService orderService;
    private final UserAddressService userAddressService;

    public PersonalController(OrderService orderService, UserAddressService userAddressService) {
        this.orderService = orderService;
        this.userAddressService = userAddressService;
    }

    /**
     * 获取一个用户的地址
     */
    @GetMapping(value = "addr", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String, Object> addr(Integer id, HttpSession session) {
        User user = (User) Global.findUser(session);
        UserAddress addr = userAddressService.findById(id);
        return Map.of("success", true, "data", addr);
    }


    //跳转到个人中心页的，订单选项卡
    @GetMapping("/orders")
    public String orders(Map<String, Object> map, HttpSession session) {
        map.put("anchor", "orders");//锚点

        User user = Global.findUser(session);
        //查询全部，可以根据需要考虑分页
        List<Order> orders = orderService.findByUserId(user.getId());

        List<UserAddress> addresses = userAddressService.findByUserId(user.getId());
        map.put("addresses", addresses);

        map.put("user",user);
        map.put("orders", orders);

        return "account";
    }

    @GetMapping("/add1rAdd")

    public String addrAdd(HttpServletRequest req) {
        return "addrAdd";
    }
    @PostMapping(value = "add1rAdd",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> saveAddr(UserAddress userAddress,HttpSession session){
        User user = Global.findUser(session);
        userAddress.setUserId(user.getId());
        boolean success = userAddressService.insert(userAddress);
        return Map.of("success",success);
    }
    @PatchMapping(value = "/add1rEdit",produces = "application/json;charset=utf-8")
    @ResponseBody
    public Map<String,Object> addrEdit(UserAddress userAddress,HttpSession session){
        User user = Global.findUser(session);
        userAddress.setUserId(user.getId());
        boolean success = userAddressService.update(userAddress);
        return Map.of("success",success);
    }
}
